<template>
  <div class="image-preview-container" @click="handleImageClick">
    <el-image
        :src="`${realSrc}`"
        fit="cover"
        :style="`width:${realWidth};height:${realHeight};`"
        :preview-src-list="[]"
    >
      <template #error>
        <div class="image-slot">
          <el-icon><picture-filled /></el-icon>
        </div>
      </template>
    </el-image>
  </div>

  <!-- 自定义预览模态框 -->
  <Teleport to="body">
    <div 
      v-if="showPreview" 
      class="custom-image-viewer"
      @click="closePreview"
    >
      <div class="custom-image-viewer__mask"></div>
      <div class="custom-image-viewer__content" @click.stop>
        <div class="custom-image-viewer__close" @click="closePreview">
          <el-icon><Close /></el-icon>
        </div>
        
        <!-- 操作工具栏 -->
        <div class="custom-image-viewer__actions">
          <div class="custom-image-viewer__actions-inner">
            <button class="custom-image-viewer__action" @click="zoomOut" title="缩小">
              <el-icon><ZoomOut /></el-icon>
            </button>
            <button class="custom-image-viewer__action" @click="zoomIn" title="放大">
              <el-icon><ZoomIn /></el-icon>
            </button>
            <button class="custom-image-viewer__action" @click="resetTransform" title="1:1">
              <span>1:1</span>
            </button>
            <button class="custom-image-viewer__action" @click="rotateLeft" title="逆时针旋转">
              <el-icon><RefreshLeft /></el-icon>
            </button>
            <button class="custom-image-viewer__action" @click="rotateRight" title="顺时针旋转">
              <el-icon><RefreshRight /></el-icon>
            </button>
          </div>
        </div>
        
        <div class="custom-image-viewer__navigation" v-if="realSrcList.length > 1">
          <button 
            class="custom-image-viewer__btn custom-image-viewer__prev"
            @click="prevImage"
            :disabled="currentIndex === 0"
          >
            <el-icon><ArrowLeft /></el-icon>
          </button>
          <button 
            class="custom-image-viewer__btn custom-image-viewer__next"
            @click="nextImage"
            :disabled="currentIndex === realSrcList.length - 1"
          >
            <el-icon><ArrowRight /></el-icon>
          </button>
        </div>
        
        <div class="custom-image-viewer__canvas">
          <img 
            :src="realSrcList[currentIndex]" 
            class="custom-image-viewer__img"
            :style="imageStyle"
            @load="onImageLoad"
            @wheel="handleWheel"
          >
        </div>
      </div>
    </div>
  </Teleport>
</template>

<script setup>
import { isExternal } from "@/utils/validate";
import { Close, ArrowLeft, ArrowRight, ZoomIn, ZoomOut, RefreshLeft, RefreshRight } from '@element-plus/icons-vue';

const props = defineProps({
  src: {
    type: String,
    default: ""
  },
  width: {
    type: [Number, String],
    default: ""
  },
  height: {
    type: [Number, String],
    default: ""
  }
});

// 预览状态
const showPreview = ref(false);
const currentIndex = ref(0);

// 图片变换状态
const transform = ref({
  scale: 1,
  rotate: 0,
  translateX: 0,
  translateY: 0
});

// 计算图片样式
const imageStyle = computed(() => {
  const { scale, rotate, translateX, translateY } = transform.value;
  return {
    transform: `scale(${scale}) rotate(${rotate}deg) translate(${translateX}px, ${translateY}px)`,
    transition: 'transform 0.3s ease'
  };
});

const realSrc = computed(() => {
  if (!props.src) {
    return;
  }
  let real_src = props.src.split(",")[0];
  if (isExternal(real_src)) {
    return real_src;
  }
  return import.meta.env.VITE_APP_BASE_API + real_src;
});

const realSrcList = computed(() => {
  if (!props.src) {
    return [];
  }
  let real_src_list = props.src.split(",");
  let srcList = [];
  real_src_list.forEach(item => {
    if (isExternal(item)) {
      return srcList.push(item);
    }
    return srcList.push(import.meta.env.VITE_APP_BASE_API + item);
  });
  return srcList;
});

const realWidth = computed(() =>
    typeof props.width == "string" ? props.width : `${props.width}px`
);

const realHeight = computed(() =>
    typeof props.height == "string" ? props.height : `${props.height}px`
);

// 处理图片点击
const handleImageClick = () => {
  if (realSrcList.value.length > 0) {
    currentIndex.value = 0;
    showPreview.value = true;
    resetTransform();
    // 防止页面滚动
    document.body.style.overflow = 'hidden';
  }
};

// 关闭预览
const closePreview = () => {
  showPreview.value = false;
  document.body.style.overflow = '';
  resetTransform();
};

// 重置变换
const resetTransform = () => {
  transform.value = {
    scale: 1,
    rotate: 0,
    translateX: 0,
    translateY: 0
  };
};

// 放大
const zoomIn = () => {
  if (transform.value.scale < 3) {
    transform.value.scale += 0.2;
  }
};

// 缩小
const zoomOut = () => {
  if (transform.value.scale > 0.2) {
    transform.value.scale -= 0.2;
  }
};

// 逆时针旋转
const rotateLeft = () => {
  transform.value.rotate -= 90;
};

// 顺时针旋转
const rotateRight = () => {
  transform.value.rotate += 90;
};

// 鼠标滚轮缩放
const handleWheel = (e) => {
  e.preventDefault();
  if (e.deltaY < 0) {
    zoomIn();
  } else {
    zoomOut();
  }
};

// 上一张图片
const prevImage = () => {
  if (currentIndex.value > 0) {
    currentIndex.value--;
    resetTransform();
  }
};

// 下一张图片
const nextImage = () => {
  if (currentIndex.value < realSrcList.value.length - 1) {
    currentIndex.value++;
    resetTransform();
  }
};

// 图片加载完成
const onImageLoad = () => {
  // 可以在这里添加图片加载完成后的逻辑
};

// 键盘事件处理
const handleKeydown = (e) => {
  if (!showPreview.value) return;
  
  switch (e.key) {
    case 'Escape':
      closePreview();
      break;
    case 'ArrowLeft':
      prevImage();
      break;
    case 'ArrowRight':
      nextImage();
      break;
  }
};

onMounted(() => {
  document.addEventListener('keydown', handleKeydown);
});

onUnmounted(() => {
  document.removeEventListener('keydown', handleKeydown);
  document.body.style.overflow = '';
});
</script>

<style lang="scss" scoped>
.image-preview-container {
  cursor: pointer;
  
  .el-image {
    border-radius: 5px;
    background-color: #ebeef5;
    box-shadow: 0 0 5px 1px #ccc;
    
    :deep(.el-image__inner) {
      transition: all 0.3s;
      cursor: pointer;
      &:hover {
        transform: scale(1.2);
      }
    }
    
    :deep(.image-slot) {
      display: flex;
      justify-content: center;
      align-items: center;
      width: 100%;
      height: 100%;
      color: #909399;
      font-size: 30px;
    }
  }
}

/* 自定义预览样式 */
.custom-image-viewer {
  position: fixed;
  top: 0;
  left: 0;
  width: 100vw;
  height: 100vh;
  z-index: 999999;
  display: flex;
  align-items: center;
  justify-content: center;
}

.custom-image-viewer__mask {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.8);
  z-index: 999998;
}

.custom-image-viewer__content {
  position: relative;
  z-index: 999999;
  max-width: 90vw;
  max-height: 90vh;
  display: flex;
  align-items: center;
  justify-content: center;
}

.custom-image-viewer__close {
  position: absolute;
  top: -40px;
  right: 0;
  width: 40px;
  height: 40px;
  background: rgba(0, 0, 0, 0.5);
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  color: white;
  font-size: 20px;
  transition: all 0.3s;
  z-index: 999999;
  
  &:hover {
    background: rgba(0, 0, 0, 0.8);
  }
}

.custom-image-viewer__actions {
  position: absolute;
  bottom: -60px;
  left: 50%;
  transform: translateX(-50%);
  z-index: 999999;
}

.custom-image-viewer__actions-inner {
  display: flex;
  align-items: center;
  background: rgba(0, 0, 0, 0.5);
  border-radius: 25px;
  padding: 8px 12px;
  gap: 8px;
}

.custom-image-viewer__action {
  width: 40px;
  height: 40px;
  background: transparent;
  border: none;
  border-radius: 50%;
  color: white;
  font-size: 16px;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: all 0.3s;
  
  &:hover {
    background: rgba(255, 255, 255, 0.2);
  }
  
  span {
    font-size: 12px;
    font-weight: bold;
  }
}

.custom-image-viewer__navigation {
  position: absolute;
  top: 50%;
  transform: translateY(-50%);
  width: 100%;
  display: flex;
  justify-content: space-between;
  pointer-events: none;
  z-index: 999999;
}

.custom-image-viewer__btn {
  width: 50px;
  height: 50px;
  background: rgba(0, 0, 0, 0.5);
  border: none;
  border-radius: 50%;
  color: white;
  font-size: 20px;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: all 0.3s;
  pointer-events: all;
  
  &:hover:not(:disabled) {
    background: rgba(0, 0, 0, 0.8);
  }
  
  &:disabled {
    opacity: 0.3;
    cursor: not-allowed;
  }
}

.custom-image-viewer__prev {
  margin-left: -25px;
}

.custom-image-viewer__next {
  margin-right: -25px;
}

.custom-image-viewer__canvas {
  display: flex;
  align-items: center;
  justify-content: center;
  max-width: 100%;
  max-height: 100%;
}

.custom-image-viewer__img {
  max-width: 100%;
  max-height: 100%;
  object-fit: contain;
  border-radius: 8px;
}
</style>
